package com.hmdp.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

//刷新Token的拦截器
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*基于session进行拦截*/
        /*  //1. 获取session
        HttpSession session = request.getSession();
        //2. 获取session中的用户
        Object user = session.getAttribute("user");
        //3. 判断用户是否存在
        if (user == null) {
            //4. 如果不存在，返回错误信息(拦截)
            response.setStatus(401);
            return false;
        }
        //5. 如果存在，保存用户信息到ThreadLocal
        UserHolder.saveUser((UserDTO) user);
        //6. 放行
        return true;*/

        /*基于token进行拦截*/
        //1. 获取token
        String token = request.getHeader("Authorization");//这里的 头名称Authorization 名称是前端的给过来的
        if(StrUtil.isBlank(token)){//判断token是否为空
            return true;
        }
        //2. 基于token获取redis中的用户  //entries自带判断是否为null
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash()
                .entries(RedisConstants.LOGIN_USER_KEY + token);
        //3. 判断用户是否存在
        if(userMap.isEmpty()){
            return true;
        }
        //5.将查询到的Hash数据转为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);//BeanUtil必须为hutool包下的
        //6. 如果存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //7. 刷新token有效期(30分钟)
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
